package org.JDBC;

// 添加必要的导入语句
import org.junit.Test;
import java.sql.*;
import java.util.Arrays;

public class BatchTest {

    private String driverClass = "com.mysql.cj.jdbc.Driver";
    private String url = "jdbc:mysql://127.0.0.1:3306/briup";
    private String user = "root";
    private String password = "1234";

    @Test
    public void test_batch() {
        Connection conn = null;
        Statement stmt = null;
        try {
//1.加载注册驱动
            Class.forName(driverClass);
//2.获取连接对象
            conn =
                    DriverManager.getConnection(url,user,password);
//3.获取Statement对象
            stmt = conn.createStatement();
//4.执行SQL语句
            String sql1 = "drop table if exists t_user";
            String sql2 = "create table t_user("
                    + "id bigint primary key,"  // 使用bigint更适合id
                    + "name varchar(50) not null,"
                    + "age int"
                    + ")";
            String sql3 = "insert into t_user(id,name,age) values(1,'tom1',21)";
            String sql4 = "insert into t_user(id,name,age) values(2,'tom2',22)";
            String sql5 = "insert into t_user(id,name,age) values(3,'tom3',23)";
            String sql6 = "update t_user set name='mary' where id>1";
            //把要执行的sql语句，添加到批处理中
            stmt.addBatch(sql1);
            stmt.addBatch(sql2);
            stmt.addBatch(sql3);
            stmt.addBatch(sql4);
            stmt.addBatch(sql5);
            stmt.addBatch(sql6);
//执行批处理中的sql语句，返回每一个语句的结果
            int[] rows = stmt.executeBatch();
//5.处理结果
            System.out.println("运行结果：rows = "+
                    Arrays.toString(rows));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
//6.释放资源
            if(stmt != null) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}